package com.erp.collect.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.collect.domain.ErpCollectProductDistributeLog;
import com.erp.collect.mapper.ErpCollectProductDistributeLogMapper;
import com.erp.collect.mapper.ErpKakaCollectProductExpandMapper;
import com.erp.collect.mapper.ErpKakaCollectProductMapper;
import com.erp.collect.mapper.ErpKakaCollectProductSkuMapper;
import com.erp.collect.service.IErpKakaCollectProductService;
import com.esotericsoftware.minlog.Log;
import com.ruoyi.collect.api.domain.ErpKakaCollectProduct;
import com.ruoyi.collect.api.domain.ErpKakaCollectProductExpand;
import com.ruoyi.collect.api.domain.ErpKakaCollectProductSku;
import com.ruoyi.collect.api.domain.bo.ErpKakaCollectProductBo;
import com.ruoyi.collect.api.domain.vo.ErpKakaCollectProductVo;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.ImageMergeUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.dto.OssUrlDto;
import com.ruoyi.system.api.domain.vo.SysOssVo;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * 采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）Service业务层处理
 *
 * @author erp
 * @date 2024-05-16
 */
@RequiredArgsConstructor
@Service
public class ErpKakaCollectProductServiceImpl implements IErpKakaCollectProductService {

    private final ErpKakaCollectProductMapper baseMapper;
    private final ErpKakaCollectProductSkuMapper skuMapper;
    private final ErpKakaCollectProductExpandMapper productExpandMapper;
    private final ErpCollectProductDistributeLogMapper distributeLogMapper;
    private final ErpKakaCollectProductExpandMapper erpKakaCollectProductExpandMapper;
    private final ErpKakaCollectProductSkuMapper erpKakaCollectProductSkuMapper;
    private final RestTemplate restTemplate;
    @Resource
    RemoteFileService remoteFileService;
    private final RemoteCollectProductService remoteCollectProductService;

    /**
     * 查询采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public ErpKakaCollectProductVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public TableDataInfo<ErpKakaCollectProductVo> queryPageList(ErpKakaCollectProductBo bo, PageQuery pageQuery) {
        bo.setOperateType("0");
        bo.setCollectUserId(SecurityContextHolder.getUserId());
        LambdaQueryWrapper<ErpKakaCollectProduct> lqw = buildQueryWrapper(bo);
        Page<ErpKakaCollectProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public List<ErpKakaCollectProductVo> queryList(ErpKakaCollectProductBo bo) {
        LambdaQueryWrapper<ErpKakaCollectProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpKakaCollectProduct> buildQueryWrapper(ErpKakaCollectProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpKakaCollectProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, ErpKakaCollectProduct::getId, bo.getId());
        lqw.eq(bo.getCategoryId() != null, ErpKakaCollectProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpKakaCollectProduct::getImageURLs, bo.getImageURLs());
        lqw.eq(StringUtils.isNotBlank(bo.getSubject()), ErpKakaCollectProduct::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpKakaCollectProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpKakaCollectProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpKakaCollectProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectProductPrice()), ErpKakaCollectProduct::getCollectProductPrice, bo.getCollectProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpKakaCollectProduct::getProductPrice, bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpKakaCollectProduct::getMobileDetail, bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpKakaCollectProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpKakaCollectProduct::getPackageWidth, bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpKakaCollectProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpKakaCollectProduct::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpKakaCollectProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpKakaCollectProduct::getCustomAttributes, bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpKakaCollectProduct::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpKakaCollectProduct::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpKakaCollectProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getModeSizeChartList()), ErpKakaCollectProduct::getModeSizeChartList, bo.getModeSizeChartList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpKakaCollectProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(bo.getCollectUserId() != null, ErpKakaCollectProduct::getCollectUserId, bo.getCollectUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOldDetailImg()), ErpKakaCollectProduct::getOldDetailImg, bo.getOldDetailImg());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpKakaCollectProduct::getRevision, bo.getRevision());
        lqw.eq(StringUtils.isNotBlank(bo.getOperateType()), ErpKakaCollectProduct::getOperateType, bo.getOperateType());
        return lqw;
    }

    /**
     * 新增采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean insertByBo(ErpKakaCollectProductBo bo) {
        ErpKakaCollectProduct add = BeanUtil.toBean(bo, ErpKakaCollectProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean updateByBo(ErpKakaCollectProductBo bo) {
        ErpKakaCollectProduct update = BeanUtil.toBean(bo, ErpKakaCollectProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpKakaCollectProduct entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采集商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * @param id
     * @return
     * @Description: 根据商品ID，获取商品所有的图片信息
     * @Author: j.zh
     * @Date: 2024/5/16
     * @Version: 4.0.0
     **/
    @Override
    public Map<String, Object> queryImgUrlById(Long id) {
        ErpKakaCollectProduct product = baseMapper.selectById(id);
        if (product == null) {
            return null;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("main", product.getImageURLs().replaceAll("\\[", "")
                .replaceAll("\\]", "").replaceAll(",", ";")
                .replaceAll("，", ";"));
        result.put("white", product.getWhite() == null ? result.get("main").toString().split(";")[0] : product.getWhite().
                replaceAll("\\[", "")
                .replaceAll("\\]", "").replaceAll(",", ";")
                .replaceAll("，", ";"));
        result.put("marketing", product.getMarketing().replaceAll("\\[", "")
                .replaceAll("\\]", "").replaceAll(",", ";")
                .replaceAll("，", ";"));
        result.put("detailImg", product.getDetailImg().replaceAll("\\[", "")
                .replaceAll("\\]", "").replaceAll(",", ";")
                .replaceAll("，", ";"));
        result.put("subject", product.getSubject());
        result.put("detail", product.getDetail());

        List<ErpKakaCollectProductSku> productSkuList = skuMapper.selectList(new LambdaQueryWrapper<ErpKakaCollectProductSku>()
                .eq(ErpKakaCollectProductSku::getCollectProductId, id));
        Map<Long, String> skuResult = new HashMap<>();
        for (ErpKakaCollectProductSku sku : productSkuList) {
            if (sku.getSkuImage() == null || sku.getSkuImage().equals("")) {
                continue;
            }
            skuResult.put(sku.getId(), sku.getSkuImage().replaceAll("\\[", "")
                    .replaceAll("\\]", "").replaceAll(",", ";")
                    .replaceAll("，", ";"));
        }
        result.put("skuImgMap", skuResult);
        return result;
    }

    /**
     * @param map
     * @return
     * @Description: 根据Map集合，更新商品所有图片
     * @Author: j.zh
     * @Date: 2024/5/16
     * @Version: 4.0.0
     **/
    @Async
    @Override
    public void updateProductImgs(Map<String, Object> map) {
        String newWhite = "";
        String newMarketing = "";
        try {
            newWhite = generateWhite(map.get("white").toString());
            newMarketing = generateMarketing(map.get("white").toString());
        } catch (Exception e) {
            Log.error("生成白底营销图失败");
            return;
        }

        ErpKakaCollectProduct product = new ErpKakaCollectProduct();
        product.setId(Long.parseLong(map.get("id").toString()));
        product.setImageURLs(map.get("main").toString());
        product.setWhite(newWhite.startsWith("http") ? newWhite : map.get("white").toString());
        product.setMarketing(newMarketing.startsWith("http") ? newMarketing : map.get("marketing").toString());
        product.setDetailImg(map.get("detailImg").toString());
        product.setSubject(map.get("subject").toString());
        product.setDetail(map.get("detail").toString());
        product.setOperateType("1");
        if (baseMapper.updateById(product) > 0) {
            // 更新sku图
            Map<String, String> skuResult = (Map<String, String>) map.get("skuImgMap");
            for (String key : skuResult.keySet()) {
                ErpKakaCollectProductSku sku = new ErpKakaCollectProductSku();
                sku.setId(Long.parseLong(key));
                sku.setSkuImage(skuResult.get(key));
                skuMapper.updateById(sku);
            }
            // 更新编辑状态
            ErpKakaCollectProductExpand productExpand = new ErpKakaCollectProductExpand();
            productExpand.setEditStatus(1l);
            productExpandMapper.update(productExpand,
                    new LambdaUpdateWrapper<ErpKakaCollectProductExpand>()
                            .eq(ErpKakaCollectProductExpand::getCollectProductId, Long.parseLong(map.get("id").toString())));
            // 插入分发记录表
            if(distributeLogMapper.selectCount(new LambdaQueryWrapper<ErpCollectProductDistributeLog>()
                    .eq(ErpCollectProductDistributeLog::getCollectProductId, Long.parseLong(map.get("id").toString()))).intValue() > 0){
                // 已有分发记录 不作处理
            }else {
                ErpCollectProductDistributeLog distributeLog = new ErpCollectProductDistributeLog();
                distributeLog.setCollectProductId(Long.parseLong(map.get("id").toString()));
                distributeLog.setSource("1688");
                distributeLog.setDistributeAe("0");
                distributeLog.setDistributeMiniShop("0");
                distributeLog.setCreateBy(SecurityContextHolder.getUserId().toString());
                distributeLog.setCreateTime(new Date());
                distributeLogMapper.insert(distributeLog);
            }
        }
    }

    /**
     * @param id
     * @param next
     * @return
     * @Description: 根据ID和左滑右滑指令，获取下一个商品图片集合
     * @Author: j.zh
     * @Date: 2024/5/16
     * @Version: 4.0.0
     **/
    public Map<String, Object> queryImgUrlByIdAndNext(Long id, Integer next) {
        ErpKakaCollectProduct product = new ErpKakaCollectProduct();
        if (next > 0) {
            product = baseMapper.selectOne(new LambdaQueryWrapper<ErpKakaCollectProduct>()
                    .eq(ErpKakaCollectProduct::getOperateType, "0")
                    .eq(ErpKakaCollectProduct::getCollectUserId, SecurityContextHolder.getUserId())
                    .gt(ErpKakaCollectProduct::getId, id)
                    .orderByAsc(ErpKakaCollectProduct::getId).last("limit 1"));
        } else {
            product = baseMapper.selectOne(new LambdaQueryWrapper<ErpKakaCollectProduct>()
                    .eq(ErpKakaCollectProduct::getOperateType, "0")
                    .eq(ErpKakaCollectProduct::getCollectUserId, SecurityContextHolder.getUserId())
                    .lt(ErpKakaCollectProduct::getId, id)
                    .orderByDesc(ErpKakaCollectProduct::getId).last("limit 1"));
        }
        return queryImgUrlById(product.getId());
    }

    /**
     * @param imgUrl
     * @return
     * @Description: 生成白底图
     * @Author: j.zh
     * @Date: 2024/5/16
     * @Version: 4.0.0
     **/
    @Override
    public String generateWhite(String imgUrl) {
        // 自动抠图
        String handle = "http://120.224.119.46:8890";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(
                handle + "/medium/remove/background?sourceImgUrl=" + imgUrl, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (200 != code) {
            return "生成失败";
        } else {
            String url = jsonObject.getString("data");

            String backgroundPic = "https://file.pbb2c.com/common-product/2023/04/25/A3A9697071CE415794AD88EA8192C309.jpg";
            String elementPic = url;
//            String newPicUrl = "D:\\testpic\\" + "" + IdUtil.fastSimpleUUID() + ".jpg";
            String newPicUrl = "/root/yida/prod/img/temp/" + IdUtil.fastSimpleUUID() + ".jpg";
            ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
            String mergeUrl = uploadNewPicToOss(newPicUrl);
            return mergeUrl;



//            // 进行套图，和白底图标签中的白底图进行套图 TODO gather模块在跑数据，不方便更新，暂时把背景图地址写死
//            R<ErpProductAtlas> atlasR = remoteCollectProductService.getByTagId(1650776561517563905L);
//
//            System.out.println("************3333***********1650776561517563905L");
//            if (atlasR.getCode() == 200) {
//
//                System.out.println("************4444***********");
//                ErpProductAtlas atlas = atlasR.getData();
//                if (!ObjectUtils.isEmpty(atlas)) {
//
//                    System.out.println("************5555***********");
//                    String backgroundPic = "https://file.pbb2c.com/" + atlas.getPictureUrl();
//                    String elementPic = url;
//                    String newPicUrl = "/root/yida/prod/img/temp/" + IdUtil.fastSimpleUUID() + ".jpg";
//                    ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
//                    String mergeUrl = uploadNewPicToOss(newPicUrl);
//                    System.out.println("************6666***********" + mergeUrl);
//                    return mergeUrl;
//                }
//            }
//            return "白底图背景为空";
        }
    }

    /**
     * @param imgUrl
     * @return
     * @Description: 生成营销图
     * @Author: j.zh
     * @Date: 2024/5/16
     * @Version: 4.0.0
     **/
    @Override
    public String generateMarketing(String imgUrl) {
        // 自动抠图
        String handle = "http://120.224.119.46:8890";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(
                handle + "/medium/remove/background?sourceImgUrl=" + imgUrl, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (200 != code) {
            return "生成失败";
        } else {
            String url = jsonObject.getString("data");

            String backgroundPic = "https://file.pbb2c.com/common-product/2023/12/13/BD5E7E09460A4ECCB5ACFAAA063367D2.jpg";
            String elementPic = url;
//            String newPicUrl = "D:\\testpic\\" + "" + IdUtil.fastSimpleUUID() + ".jpg";
            String newPicUrl = "/root/yida/prod/img/temp/" + IdUtil.fastSimpleUUID() + ".jpg";
            ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
            String mergeUrl = uploadNewPicToOss(newPicUrl);
            System.out.println(mergeUrl);
            return mergeUrl;

//            // 进行套图，和白底图标签中的白底图进行套图 TODO gather模块在跑数据，不方便更新，暂时把背景图地址写死
//            R<ErpProductAtlas> atlasR = remoteCollectProductService.getByTagId(1734451666229985281L);
//            if (atlasR.getCode() == 200) {
//                ErpProductAtlas atlas = atlasR.getData();
//                if (!ObjectUtils.isEmpty(atlas)) {
//                    String backgroundPic = "https://file.pbb2c.com/" + atlas.getPictureUrl();
//                    String elementPic = url;
////                    String newPicUrl = "D:\\testpic\\" + "" + IdUtil.fastSimpleUUID() + ".jpg";
//                    String newPicUrl = "/root/yida/prod/img/temp/" + IdUtil.fastSimpleUUID() + ".jpg";
//                    ImageMergeUtils.overlyingImageTest(backgroundPic, elementPic, newPicUrl);
//                    String mergeUrl = uploadNewPicToOss(newPicUrl);
//                    System.out.println(mergeUrl);
//                    return mergeUrl;
//                }
//            }
//            return "营销图背景为空";
        }
    }



    /**
     * 根据图片地址，上传图片
     *
     * @param newPicUrl
     * @return
     */
    private String uploadNewPicToOss(String newPicUrl) {
//        File file = new File(newPicUrl);
//        String name = file.getName();
//        InputStream fileInputStream = null;
//        try {
//            fileInputStream = new FileInputStream(file);
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        }
//        MultipartFile multipartFile = null;
//        try {
//            multipartFile = new MockMultipartFile(name, name, ContentType.APPLICATION_OCTET_STREAM.toString(),
//                    fileInputStream);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        OssUrlDto dto = new OssUrlDto();
        dto.setOldUrl(newPicUrl);
        R<Object> objectR = remoteFileService.uploadUrl(dto);
        if (objectR.getCode() != 200) {
            return "上传oss异常";
        }

        String toJSONString = JSONObject.toJSONString(objectR.getData());
        SysOssVo upload = JSONObject.parseObject(toJSONString, SysOssVo.class);
        return upload.getUrl();
    }

}
